package xiancheng.communication;

/**
 * @author Mr.ma
 * @since 2022/11/1 21:32
 * 线程通信
 **/
public class Test11 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        Boy boy = new Boy(bank);
        Girl girl = new Girl(bank);
        Thread thread1 = new Thread(boy, "小明");
        Thread thread2 = new Thread(girl, "小红");
        thread1.start();
        thread2.start();
    }
}
class Boy implements Runnable{
    Bank bank = new Bank();
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            bank.save();
        }
    }
    public Boy() {
    }
    public Boy(Bank bank) {
        this.bank = bank;
    }
}
class Girl implements Runnable{
    Bank bank = new Bank();
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            bank.draw();
        }
    }
    public Girl() {
    }
    public Girl(Bank bank) {
        this.bank = bank;
    }
}
class Bank {
    private int money = 0;
    /**
     * 取钱
     */
    public synchronized void draw(){
        if (money <= 0) {
            notify();
            System.out.println(Thread.currentThread().getName()+"余额不足,等待被唤醒线程存钱");
        }
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        money = money - 1000;
        System.out.println(Thread.currentThread().getName() + "取出了1000元，还剩下" + money);
        notify();
    }

    /**
     * 存钱
     */
    public synchronized void save(){
        if (money > 0) {
            notify();
            System.out.println(Thread.currentThread().getName()+"唤醒取钱线程");
        }
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        money = money + 1000;
        System.out.println(Thread.currentThread().getName() + "存入了1000元，还剩下" + money);
        notify();
    }
}